package com.taoban.shopdata.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taoban.shopdata.entity.PriceUpdatedCommitResult;

public class ThreadPoolExecutor1 extends ThreadPoolExecutor {
	public static final Log mLog = LogFactory.getLog(ThreadPoolExecutor1.class);
   
	/**
	 * 标识唯一的商城+用户信息，利用md5表示
	 */
	private List<String> mallReadyStatus=Collections.synchronizedList(new ArrayList<String>());
	

	public ThreadPoolExecutor1(int corePoolSize, int maximumPoolSize,
			long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
		// TODO Auto-generated constructor stub
	}
	public  void beforeExecute(Thread t, Runnable r){
		ShopDataConsumerThread shopDataConsumerThread=(ShopDataConsumerThread)r;
		
	}
	protected void afterExecute(Runnable r, Throwable t) {
		ShopDataConsumerThread shopDataConsumerThread=(ShopDataConsumerThread)r;
		readyForTask(shopDataConsumerThread.getPriceUpdatedCommitResult());

	}
	/**
	 * @param task
	 * @return
	 * 
	 */
	private boolean isTaskReady(PriceUpdatedCommitResult task){
		boolean isReady=false;
	    if(!this.mallReadyStatus.contains(""+task.getMallType()+"_false")){
	    	isReady=true;
	    }
		return isReady;
	}
	public   void readyForTask(PriceUpdatedCommitResult task){
		 String o = ""+task.getMallType()+"_false";
		if(this.mallReadyStatus.contains(o)){
		    	mallReadyStatus.remove(o);
		    }
	}
	public void fetchTaskAndExecute(final BlockingQueue<PriceUpdatedCommitResult> tasks){
		/*this.setRejectedExecutionHandler(new RejectedExecutionHandler() {
			
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				// TODO Auto-generated method stub
				
			}
		});*/
		mLog.info("从队列中获取任务进行处理");
		PriceUpdatedCommitResult currentPriceUpdatedCommitResult=null;
		
		
				 currentPriceUpdatedCommitResult=tasks.poll();
			
			if(currentPriceUpdatedCommitResult==null){
				return;
			}
		    if(!isTaskReady(currentPriceUpdatedCommitResult)){
		    	mLog.debug("此任务所在商城已在运行，请稍后重新请求！");
		    	tasks.add(currentPriceUpdatedCommitResult);
		    	return;
		    }
		    
			mallReadyStatus.add(""+currentPriceUpdatedCommitResult.getMallType()+"_false");
			
			this.execute(new ShopDataConsumerThread(currentPriceUpdatedCommitResult));
	}
}
